//
//  HPYOAuthViewController.swift
//  SwiftVVBo
//
//  Created by hepeiyong on 16/8/11.
//  Copyright © 2016年 hpyhn. All rights reserved.
//
import UIKit
import SVProgressHUD
class HPYOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
        // 判断url 是否为nil
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)") else{
            return
        }
        // 设置代理
        webView.delegate = self
        // 实例化request
        let request = NSURLRequest(URL: url)
        // 记载request
        webView.loadRequest(request)

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    // MARK: - 监听方法
    // 取消
    @objc private func cancelAction(){
        dismissViewControllerAnimated(false, completion: nil)
    }
    // 自动填充
    @objc private func autofillAction(){
        printLog("自动填充")
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWd)'"
        // js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }

    // MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HPYOAuthViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HPYOAuthViewController.autofillAction))
        navigationItem.title = "微博登录"
    }

    // MARK: -  懒加载控件
    private lazy var webView: UIWebView = UIWebView()

}

extension HPYOAuthViewController: UIWebViewDelegate {
    /*
     - 监听 webView 将要加载的request
     - 如果不实现 默认 返回true
     - 如果返回 false  停止加载requet
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 判断urlString 是否为nil  而且 它的前缀是否为我们设置的回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
            // query 请求参数
            // 判断是否为nil
            if let query = request.URL?.query{
                // 获取code(截取字符串)
                let code = query.substringFromIndex("code=".endIndex)
                printLog("终于等到你还好没放弃:\(code)")
                HPYUserAccountViewModel.sharedTools.getUserAccount(code, finish: { (isSuccess) -> () in
                    if !isSuccess {
                        printLog("请求失败")
                        return
                    }
                    printLog("请求成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        // 发送通知 切换根控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSWITCHROOTVCNOTIFICATION, object: "oauth")
                    })
                })
                return false
            }

        }
        return true
    }

    // 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    // 加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
         SVProgressHUD.dismiss()
    }
    // 加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.setStatus("加载失败")
    }
}

